package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrSequenceOf;
import org.road0329.dlt698.asn1.axdr.AxdrType;
import org.road0329.dlt698.opt.ProxySetOfReads;

import java.io.IOException;

public class ProxyReqOADDATA extends AxdrType {
    private byte[] dataCode = null;
    private TSA tsa = null;
    private Unsigned16 maxWait = null;
    private ProxySetOfReads reads = null;

    public ProxyReqOADDATA() {
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(TSA tsa, Unsigned16 maxWait, ProxySetOfReads reads) {
        this.tsa = tsa;
        this.maxWait = maxWait;
        this.reads = reads;
    }

    public void setTsa(TSA tsa) {
        this.tsa = tsa;
    }

    public void setMaxWait(Unsigned16 maxWait) {
        this.maxWait = maxWait;
    }

    public void setReads(ProxySetOfReads reads) {
        this.reads = reads;
    }

    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.tsa = new TSA();
        codeLength += this.tsa.decode(input);
        this.maxWait = new Unsigned16();
        this.maxWait.setConst();
        codeLength += this.maxWait.decode(input);
        this.reads = new ProxySetOfReads();
        codeLength += this.reads.decode(input);
        return codeLength;
    }

    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength = 0;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (int i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if (this.tsa != null && this.reads != null && this.maxWait != null) {
                codeLength += this.reads.encode(output);
                codeLength += this.maxWait.encode(output);
                codeLength += this.tsa.encode(output);
            } else {
                throw new RuntimeException("tsa, maxWait, or reads is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.toByteArray();
    }

    @Override
    public String toString() {
        if (this.tsa != null && this.maxWait != null && this.reads != null) {
            return "sequence: {" + "tsa: " + this.tsa + ", maxwait: " + this.maxWait + ", reads: " + this.reads + "}";
        } else {
            return "tsa, maxWait, or reads is null";
        }
    }
}



